package cn.com.callback

import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.HttpClientUtil
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpGet
import org.apache.http.entity.mime.content.ContentBody
import org.apache.http.entity.mime.content.FileBody
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClientBuilder
import net.sf.json.JSONArray;
import javax.activation.MimetypesFileTypeMap
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import org.apache.commons.lang.StringUtils

import java.text.SimpleDateFormat;

/**
 *
 * @Title: 上传文件接口
 * @Author: Rick*
 * @Date 2022/9/9
 *
 */
public class apiFileUpload implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiFileUpload.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        // 初始化参数
        String apipram = "";
        JSONObject resultJson = new JSONObject();
        //根据不同的调用方式获取参数
        String getMethod = request.getMethod();
        if (getMethod.equals("GET")) {
            apipram = request.getQueryString();
            log.info("接收调用GET参数信息：" + apipram);
        } else if (getMethod.equals("POST")) {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                apipram += line;
            }
            log.info("接收调用POST报文信息：" + apipram);
        }


        //参数处理
        JSONObject inJson = JSONObject.fromObject(apipram);
        String Re_Filepath = KHUtil.GetSFJV(inJson, "Filepath");     //原始文件路径
        String Re_Workorderid = KHUtil.GetSFJV(inJson, "Workorderid");     //三高工单ID

        if (Re_Filepath.equals("") || Re_Workorderid.equals("")) {
            resultJson.put("resultcode", "-1");
            resultJson.put("resultmessage", "未传递正确参数！");
            return resultJson;
        }


        //校验上传接口地址、关联接口地址
        String UPLOAD_URL = KHDBConfig.getAPIURL(eliteBean, "3H_UPLOADFILE_URL");
        String WORKLINK_URL = KHDBConfig.getAPIURL(eliteBean, "3H_addRangeAttachment");
        if (UPLOAD_URL.equals("") || UPLOAD_URL.equals("null") || WORKLINK_URL.equals("") || WORKLINK_URL.equals("null")) {
            resultJson.put("resultcode", "-2");
            resultJson.put("resultmessage", "未配置接口地址！");
            return resultJson;
        }


        try {
            //上传附件,并解析返回值
            String resultString = UploadFile(eliteBean, UPLOAD_URL, Re_Filepath);
            log.debug("resultString：" + resultString);
            //读取上传附件返回值
            JSONObject resultjson = JSONObject.fromObject(resultString);
            String fileId = KHUtil.GetSFJV(resultjson, "fileId");
            String url = KHUtil.GetSFJV(resultjson, "url");
            String downloadUrl = KHUtil.GetSFJV(resultjson, "downloadUrl");
            String fileType = KHUtil.GetSFJV(resultjson, "fileType");
            String fileSize = KHUtil.GetSFJV(resultjson, "fileSize");
            String fileHash = KHUtil.GetSFJV(resultjson, "fileHash");
            String originFileName = KHUtil.GetSFJV(resultjson, "originFileName");

            //关联附件ID和工单ID，传递上传附件的返回值
            if (!fileId.equals("")) {
                String linkdata = addRangeAttachment(eliteBean, WORKLINK_URL, Re_Workorderid, fileId, url, downloadUrl, fileType, fileSize, fileHash, originFileName);
                resultJson.put("resultcode", "1");
                resultJson.put("resultmessage", "附件成功关联工单");
                //resultJson.put("resultinfo", "详细信息"+linkdata);
                return resultJson;
            }else {
                resultJson.put("resultcode", "-3");
                resultJson.put("resultmessage", "未上传成功！");
                //resultJson.put("resultinfo", "详细信息"+resultString);
                return resultJson;

            }
        } catch (Exception e) {
            log.error("内部错误", e);
            resultJson.put("resultcode", "-99");
            resultJson.put("resultmessage", "调用失败:" + e);
            resultJson.put("data", "");
            return resultJson;
        }
    }


/**
 * 方法: 调用三高接口上传附件
 */
    private static String UploadFile(EliteBean eliteBean, String UPLOAD_URL, String Re_Filepath) {
        JSONObject resultJson = new JSONObject();
        try {
            // 将文件缓存本地
            String FaxTMF = KHDBConfig.getParam(eliteBean, "FaxTMF");
            FaxTMF = KHUtil.isNull(FaxTMF) ? "C:\\" : FaxTMF;
            log.debug("文件下载路径：" + FaxTMF);
            String saveFile = httpDownloadFile(Re_Filepath, null, null, FaxTMF);
            log.debug("文件下载结果：" + saveFile);

            // 读取文件
            File file = new File(saveFile);
            String mimeType = new MimetypesFileTypeMap().getContentType(file);
            log.debug("文件MimeType：" + mimeType);

            Map<String, ContentBody> reqParam = new HashMap<String, ContentBody>();
            reqParam.put("file", new FileBody(file, mimeType));

            String httpRes = HttpClientUtil.postFileMultiPart(UPLOAD_URL, reqParam);
            log.debug("上传三高附件结果:" + httpRes);
            return StringUtils.strip(httpRes, "[]");
        } catch (Exception e) {
            log.error("上传错误", e);
            resultJson.put("resultcode", "-99");
            resultJson.put("resultmessage", "调用失败:" + e);
            resultJson.put("data", "");
            return resultJson;
        }
    }


/**
 * 方法: 调用三高接口关联附件与工单ID
 */
    private static String addRangeAttachment(EliteBean eliteBean, WORKLINK_URL, Re_Workorderid, fileId, url, downloadUrl, fileType, fileSize, fileHash, originFileName) {
        JSONObject resultJson = new JSONObject();

        try {
            //生成头部
            Map<String, String> headMap = new HashMap<String, String>();
            headMap.put("Content-Type", "application/json;");
            Date date = new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            //生成请求内容
            JSONObject infojson = new JSONObject();
            infojson.put("fileId", fileId); //文件id
            infojson.put("fileHash", fileHash); //文件hash
            infojson.put("fileName", originFileName); //文件名称
            infojson.put("fileSize", fileSize); //文件大写
            infojson.put("fileType", fileType); //文件类型
            infojson.put("mediaType", 1);//1:照片 2:视频 3:音频
            infojson.put("previewUrl", url); //预览url
            infojson.put("fileUrl", downloadUrl); //文件url
            infojson.put("uploader", 1); //上传人，但不能传递中文，不知道传什么
            infojson.put("uploadPDA", "string"); //未知，不知道干啥的
            infojson.put("uploadTime", df.format(date)); //上传时间
            infojson.put("uploadPDA", "string"); //未知，不知道干啥的
            infojson.put("attachmentStatus", 0);//未知，不知道干啥的
            infojson.put("relationType", 1);//未知，不知道干啥的
            infojson.put("relationNo", Re_Workorderid); //未知，但应该有一个是工单ID
            infojson.put("receiptNo", Re_Workorderid);//未知，但应该有一个是工单ID
            infojson.put("taskNo", Re_Workorderid);//未知，但应该有一个是工单ID

            JSONArray array = new JSONArray();
            array.add(infojson);
            log.debug("三高工单关联附件报文:" + array.toString());
            String resultpost = Util.doHttpPostUseHead(WORKLINK_URL, array.toString(), "UTF-8", 10000, 0, headMap);
            log.debug("三高工单关联附件接口返回:" + resultpost);
            String strresult = StringUtils.strip(resultpost, "[]");
            JSONObject strjson = JSONObject.fromObject(strresult);
            String linkdata = KHUtil.GetSFJV(strjson, "data");
            if (linkdata.equals("")) {
                resultJson.put("resultcode", "-3");
                resultJson.put("resultmessage", "三高关联接口调用后错误！");
                return resultJson;
            }else{
                return linkdata;
            }
        } catch (Exception e) {
            log.error("关联错误", e);
            resultJson.put("resultcode", "-99");
            resultJson.put("resultmessage", "调用失败:" + e.getMessage());
            resultJson.put("data", "");
            return resultJson;
        }
    }


    //文件下载方法
    public static String httpDownloadFile(String url, Map<String, String> headers, String encode, String savePath) {

        log.debug("httpDownloadFile url:" + url + " savePath:" + savePath);

        if (encode == null) {
            encode = "utf-8";
        }
        CloseableHttpResponse httpResponse = null;
        CloseableHttpClient closeableHttpClient = null;

        FileOutputStream fs = null;
        InputStream inputStream = null;
        String saveFile = "";
        String filename = "";
        int bytesum = 0;
        int byteread = 0;

        try {
            closeableHttpClient = HttpClientBuilder.create().build();
            HttpGet httpGet = new HttpGet(url);
            //设置header
            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpGet.setHeader(entry.getKey(), entry.getValue());
                }
            }

            httpResponse = closeableHttpClient.execute(httpGet);

            try {
			
				try {
					filename = url.substring((url.lastIndexOf('/') + 1));
					//filename = URLDecoder.decode(httpResponse.getHeaders("Content-Disposition")[0].getValue().substring(21), "UTF-8").replace("\"", "");
					inputStream = httpResponse.getEntity().getContent();
				} catch (Exception e) {
					log.error("解析文件下载头获取文件名失败", e);
					//filename = KHUtil.getNameWithoutSuffix(url);
					
				}
							

                saveFile = savePath + "/" + KHUtil.getRandomString(6).toUpperCase(Locale.ROOT) + "_" + filename;
                fs = new FileOutputStream(saveFile);
                byte[] buffer = new byte[1204];

                while ((byteread = inputStream.read(buffer)) != -1) {
                    bytesum += byteread;
                    fs.write(buffer, 0, byteread);
                }
                System.out.println(filename);
            } catch (Exception e) {
                log.error("httpDownloadFile 下载文件异常1", e);
            }

        } catch (Exception e) {
            log.error("httpDownloadFile 下载文件异常2", e);
        } finally {
            try {
                //关闭连接、释放资源
                httpResponse.close();
            } catch (IOException e) {
                log.warn("httpDownloadFile httpResponse.close()异常" + e.getMessage());
            }
            try {
                //关闭连接、释放资源
                inputStream.close();
            } catch (IOException e) {
                log.warn("httpDownloadFile inputStream.close()异常" + e.getMessage());
            }
            try {
                //关闭连接、释放资源
                fs.close();
            } catch (IOException e) {
                log.warn("httpDownloadFile fs.close异常" + e.getMessage());
            }
            try {
                //关闭连接、释放资源
                closeableHttpClient.close();
            } catch (IOException e) {
                log.warn("httpDownloadFile closeableHttpClient.close()异常" + e.getMessage());
            }
        }

        log.debug("当前文件下载路径:" + saveFile);
        return saveFile;
    }


}
